package com.yangli.leecode.mashib.interview;

/**
 * @Description
 * @Author liyang
 * @Date 2023/3/9 15:41
 */
public class FortyOne {
    public static void main(String[] args){

        System.out.println(FortyOne.pow(1.1, 10));
        System.out.println(FortyOne.sqrt(65));

    }

    // 0050
    public static double pow(double x, int n){
        if (n == 0) {
            return 0D;
        }
        int pow = Math.abs(n == Integer.MIN_VALUE ? n + 1 : n);//当n为最小值时候，不能取绝对值，加1，最后的时候再乘一遍x
        double t = x;
        double ans = 1D;
        while (pow != 0) {
            if ((pow & 1) == 1) {
                ans *= t;
            }
            t *= t;
            pow = pow >> 1;
        }
        if (n == Integer.MIN_VALUE) {
            ans *= x;
        }
        return n > 0 ? ans : 1 / ans;

    }

    // 0069 开更号，向下取整
    public static int sqrt(int n){
        if (n == 0) {
            return 0;
        }
        if (n < 4) {
            return 1;
        }
        int l = 1;
        int r = n;
        int mid = 0;
        int ans = 1;
        while (l <= r) {//标准的二分法条件l<=r 循环 l = l+1;r = r-1; 没必要mid = r/l,这样就无限循环不能退出了
            mid = (l + r) / 2;
            if (mid * mid <= n) {
                ans = mid;
                l = l + 1;
            } else {
                r = r - 1;

            }
        }

        return ans;
    }
}
